const fs = require("fs")
const path = require("path")
const cheerio = require("cheerio")
const axios = require("axios")
const { html2md } = require("./md-util")
const { msg2signature } = require('./string-util')
const { log } = require("console")

/* 获取所有模块和文章连接 */
function getModuleLinks() {
    const fpath = path.resolve("..", "temp", "module-links.html")
    const html = fs.readFileSync(fpath).toString()
    // console.log(html);

    /* 
    [
        {
            name:"Vue",
            arr:[
                {
                    title:"",
                    href:""
                }
            ]
        }
    ]
    */
    const mods = []

    const $ = cheerio.load(html)
    $("p.sidebar-heading>span").each(
        (i, el) => {
            let modName = el.children[0].data
            modName = modName.slice(0, modName.indexOf("系列"))

            console.log(modName);
            // console.log("nextSibling",el.parent.nextSibling.nextSibling.name);

            const arr = []
            let ul = el.parent.nextSibling.nextSibling
            // console.log("ul=",ul);

            ul.children.forEach((li) => {
                // console.log("li.name", li["name"]);

                if (li["name"] === "li") {
                    let a = li.children[0]
                    // console.log("a=", a);

                    arr.push({
                        title: a.children[0].data,
                        href: a.attribs.href
                    })
                }

            });

            mods.push({
                name: modName,
                arr
            })
        }
    )

    // console.log("mods=", JSON.stringify(mods));
    fs.writeFileSync(
        path.resolve("module-links.json"),
        JSON.stringify(mods)
    )
    console.log("done!");


}

/* 获取html内容的markdown */
function getContentMarkdown(href, dir = "") {
    // /interview/vue/spa.html
    axios.get(`https://vue3js.cn${href}`)

        .then(function (response) {
            let html = response.data

            let nStart = html.indexOf(`<h2 id="参考文献">`)
            html = html.slice(0, nStart) + "</div>"

            const $ = cheerio.load(html)
            // console.log("text=", $("div.theme-default-content").text());
            const fpath = path.join("..", "public", "mds", dir, (href.slice(href.lastIndexOf("/")) + ".md"))
            // console.log("fpath=", fpath);

            html2md(
                $("div.theme-default-content").html(),
                fpath
            )
        })

        .catch(function (error) {
            console.log("err=", error);
        });
}

// getContentMarkdown("/interview/design/design.html")

/* 开始爬取面试官 + 生成文章markdown */
function spiderVue3JsCnInterview() {
    const modLinks = JSON.parse(
        fs.readFileSync(path.resolve("..", "public/data/module-links.json"))
    )
    // console.log(modLinks);

    modLinks.forEach(
        ({ name, arr }) => {
            // console.log(name, arr);
            // fs.mkdirSync(path.resolve("..","public/mds/",name))

            arr.forEach(
                ({ title, href }) => {
                    getContentMarkdown(href, name)
                }
            )
        }
    )

    console.log("ok");
}

/* 给module-links.json修改markdown访问路由 + 生成视频文件路由 */
function fn3() {
    let str = fs.readFileSync("./module-links.json").toString()
    let arr = JSON.parse(str)

    arr.forEach(
        mod => {
            mod.arr.forEach(
                question => {
                    // /interview/vue/vue.html
                    question.href = question.href.slice(10) + ".md"
                    question.video = question.href.slice(0, -3) + ".mp4"
                }
            )
        }
    )

    fs.writeFileSync("./out.json", JSON.stringify(arr))
    console.log("done!");

}

/* 修改markdown文件 */
(function () {
    let str = fs.readFileSync("./temp.md").toString()
    // console.log(str);

    /* [#](#一、组件是什么) 一、组件是什么 */
    str = str.replace(
        /^\[#\]\(#\S+?\)\s+/gm,
        sub => {
            console.log("sub1=", sub);
            return "# "
        }
    )

    /* ### [#](#编写形式) 编写形式 */
    str = str.replace(
        /\s\[#\]\(#\S+?\)\s/gm,
        sub => {
            console.log("sub2=", sub);
            return " "
        }
    )

    /* 代码行号 */
    // const regCode = /\n(.+)\n\n(\d+\s{2}\n)\n/gm
    const regCode = /(\s+\n)(\n)(\d+\s{2}\n)+\n/g
    str.replace(
        regCode,
        sub => {
            console.log("sub3=", sub);
            return " "
        }
    )


    // fs.writeFileSync("./out.md", str)
    // console.log("done!");
})()
